package com.supermarket.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.supermarket.entity.Purchase;
import com.supermarket.listener.PurchaseListener;
import com.supermarket.mapper.PurchaseMapper;
import com.supermarket.service.PurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
@Service
public class PurchaseServiceImpl implements PurchaseService {
    @Autowired
    private PurchaseMapper purchaseMapper;

    @Override
    public List<Purchase> findPurchaseAll() {return purchaseMapper.findPurchaseAll();}

    @Override
    public List<Purchase> findByPage(){return purchaseMapper.findByPage();}
    @Override
    public Integer findCount(){return  purchaseMapper.findCount();}
    @Override
    public void add(Purchase purchase) {
        purchaseMapper.add(purchase);
    }
    @Override
    public void deleteById(Integer purchaseID){ purchaseMapper.deleteById(purchaseID);}
    @Override
    public void updatePurchase(Purchase purchase) {
        purchaseMapper.updatePurchase(purchase);
    }
    @Override
    public void deleteByIds(Integer [] ids){  purchaseMapper.deleteByIds(ids);}

    @Override
    public List<Purchase> findByIds(Integer[] ids) {
        return purchaseMapper.findByIds(ids);
    }
    @Override
    public void save(MultipartFile file) {
        // 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
        // 写法3：
        //fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";


        InputStream inputStream = null;

        //通过流来读取上传的文件
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        EasyExcel.read(inputStream,Purchase.class,new PurchaseListener(purchaseMapper)).sheet().doRead();
    }
}
